import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// AddBook类继承HttpServlet，用于处理添加图书的请求
 @WebServlet("/add_book")
 public class AddBook extends HttpServlet {
 private static final long serialVersionUID = 1L;

// 数据库连接相关配置信息
 private static final String URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";

// 处理GET请求，根据传入的图书相关信息添加图书并返回相应结果给客户端
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置跨域请求相关头信息
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
 response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
                                          // 设置响应内容类型为JSON格式
 response.setContentType("application/json;charset=UTF-8");
 PrintWriter out = response.getWriter();

 // 获取要添加图书的编号（从请求参数中获取）
  String bookNumber = request.getParameter("number");
        String bookName = request.getParameter("name");
        String bookAuthor = request.getParameter("author");
  if (bookNumber == null || bookNumber.isEmpty() || bookName == null || bookName.isEmpty() || bookAuthor == null || bookAuthor.isEmpty()) {
            
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书编号、名称和作者不能为空");
            out.println(errorJson.toString());
            out.close();
             return;
        }

        
         boolean addResult = addBook(bookNumber, bookName, bookAuthor);
        JSONObject resultJson = new JSONObject();
        if (addResult) {
            resultJson.put("message", "图书添加成功");
        } else {
            resultJson.put("error", "图书添加失败");
        }

        out.println(resultJson.toString());
        out.close();
    }

    
     public boolean addBook(String bookNumber, String bookName, String bookAuthor) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
         try {
            
             Class.forName("com.mysql.cj.jdbc.Driver");
            
             connection = DriverManager.getConnection(URL, USER, PASSWORD);
            
            String sql = "INSERT INTO t_book (number, name, author) VALUES (?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, bookNumber);
            preparedStatement.setString(2, bookName);
            preparedStatement.setString(3, bookAuthor);
            
            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            
             try {
                if (preparedStatement!= null) preparedStatement.close();
                if (connection!= null) connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
                                                 
